<template>
  <div class="script-tree">
    <el-tree
      style="height: 100%;"
      :data="data"
      :props="props"
      show-checkbox
      @check-change="handleCheckChange"
    ></el-tree>
  </div>
</template>

<script>
import { getScriptList } from '@/api/script'

export default {
  data () {
    return {
      props: {
        label: 'name',
        children: 'zones'
      },
      count: 1,
      data: []
    }
  },
  created () {
    this.load()
  },
  methods: {
    load () {
      getScriptList().then(data => {
        console.log(data)
        const result = this.formatTree(data, 'scriptName')
        this.data = result
      })
    },

    formatTree (list, label) {
      const result = []
      for (let index = 0; index < list.length; index++) {
        const item = list[index]
        const resultItem = {}
        resultItem[this.props.label] = item[label]
        resultItem[this.props.children] = null
        result.push(resultItem)
      }
      return result
    },

    handleCheckChange (data, checked, indeterminate) {
      console.log(data, checked, indeterminate)
    },
    handleNodeClick (data) {
      console.log(data)
    },
    loadNode (node, resolve) {
      if (node.level === 0) {
        return resolve([{ name: 'region1' }, { name: 'region2' }])
      }
      if (node.level > 3) return resolve([])

      var hasChild
      if (node.data.name === 'region1') {
        hasChild = true
      } else if (node.data.name === 'region2') {
        hasChild = false
      } else {
        hasChild = Math.random() > 0.5
      }

      setTimeout(() => {
        var data
        if (hasChild) {
          data = [{
            name: 'zone' + this.count++
          }, {
            name: 'zone' + this.count++
          }]
        } else {
          data = []
        }

        resolve(data)
      }, 500)
    }
  }
}

</script>
<style lang='scss' scoped>
.script-tree {
  height: 100%;
}
</style>
